<template>
	<view class="container">
		<view class="one"  v-if="isflag">
			<!-- 顶部导航栏 -->
			<view class="header">
				<view class="title">管理收货地址</view>
				<view class="new-address" @click="isflag=!isflag">新建</view>
			</view>
			<!-- 地址列表 -->
			<view class="address-list">
				<!-- 地址项 -->
				<view class="address-item" v-for="(item, index) in addressList" :key="index" >
					<view class="address-info" @click="selectaddress(item)">
						<view class="user-info">
							<text class="name">{{ item.name }}</text>
							<text class="phone">{{ item.phone }}</text>
						</view>
						<view class="address-detail">{{item.department}}{{item.houseNumber}}</view>
					</view>
					<view class="edit-icon">
						<image :src="Config.API_HOST + '/imgs/编辑.png'" mode="" class="edit" @click="edit(item.id)"></image>
					</view>
				</view>
			</view>
		</view>
		<!-- 新建 -->
		<view class="two" v-if="!isflag">
			<view class="header">
				<view class="title">管理收货地址</view>
				<view class="new-address" @click="save">保存</view>
			</view>
			 <view class="form-container">
			      <view class="form-item">
			        <label>所在城市:</label>
			        <view class="city-input-container">
			          <input type="text" placeholder="如杭州市" v-model="address.city" list="cityList">
			          <picker mode="selector" :range="cityList" @change="bindCityChange">
			            <view class="city-picker"><image :src="Config.API_HOST+'/imgs/选择器展开.png'" mode="" class="select"></image></view>
			          </picker>
			        </view>
			      </view>
			      <view class="form-item">
			        <label>小区/大厦/学校:</label>
			        <input type="text" placeholder="如杭师大仓前校区" v-model="address.department">
			      </view>
			      <view class="form-item">
			        <label>楼号-门牌号:</label>
			        <input type="text" placeholder="A号楼B层" v-model="address.houseNumber">
			      </view>
			      <view class="form-item">
			        <label>收货人:</label>
			        <input type="text" placeholder="请填写收货人的姓名" v-model="address.name">
			      </view>
			      <view class="form-item">
			        <label>联系电话:</label>
			        <input type="text" placeholder="请填写收货手机号" v-model="address.phone">
			      </view>
			    </view>
		</view>
	</view>
</template>

<script setup>
import { ref } from 'vue';
import {onShow } from "@dcloudio/uni-app";
import Config from '@/config.js';
const isflag=ref(true)
const id=ref()
const address = ref({
  city: '',
  department: '',
  houseNumber: '',
  name: '',
  phone: '',
});
// 地址列表数据
const addressList = ref([]);
const undate=()=>{
  const token = uni.getStorageSync('token');
  if (!token) {
	uni.navigateTo({
		url:"/pages/login/index"
	})
    return;
  }
  uni.request({
    url:Config.API_HOST+"/address?token=" + token,
    success: (res) => {
      addressList.value=res.data
    }
  })
}

// 保存
const save=()=>{
    const token = uni.getStorageSync('token');
    if(!token){
        uni.showToast({
            title: '请先登录',
            icon: 'none',
            duration: 2000
        });
        return;
    }

    // 非空验证
    const requiredFields = ['city', 'department', 'houseNumber', 'name', 'phone'];
    for (const field of requiredFields) {
        if (!address.value[field] || address.value[field].trim() === '') {
            uni.showToast({
                title: `请填写${field === 'phone' ? '联系电话' : field === 'city' ? '所在城市' : field === 'department' ? '小区/大厦/学校' : field === 'houseNumber' ? '楼号-门牌号' : '收货人'}`,
                icon: 'none',
                duration: 2000
            });
            return;
        }
    }
    
    // 手机号正则验证
    const phonePattern = /^1[3-9]\d{9}$/;
    if (!phonePattern.test(address.value.phone)) {
        uni.showToast({
            title: '请输入有效的手机号',
            icon: 'none',
            duration: 2000
        });
        return;
    }
	uni.request({
		url:Config.API_HOST+"/address",
		success: (res) => {
			const carts = res.data;
			const existingItem = carts.find(cartItem => cartItem.id == id.value);
			if (existingItem) {
				uni.request({
					url: `${Config.API_HOST}/address/${existingItem.id}`,
					method: 'PUT',
					data: {
						...address.value,
					},
					success: (res) => {
					undate()
					}
				})
				isflag.value=true
				address.value={
				city: '',
				department: '',
				houseNumber: '',
				name: '',
				phone: ''
				}
		}else{
			uni.request({
				url:Config.API_HOST+"/address",
				method:"POST",
				data:{
					...address.value,
					token: uni.getStorageSync('token')
				},
				success: (res) => {
					undate()
				}
			})
			isflag.value=true
			address.value={
			city: '',
			department: '',
			houseNumber: '',
			name: '',
			phone: ''
			}
		}
		}
	})
}
// 编辑
const edit=(addressId)=>{
	isflag.value=false
	uni.request({
	    url: Config.API_HOST + "/address?id="+addressId,
	    success: (res) => {
	       const { city, department, houseNumber, name, phone } = res.data[0];
	          address.value = {
	              city,
	              department,
	              houseNumber,
	              name,
	              phone
	          };
			  id.value=res.data[0].id
	    },
	});
}
const selectaddress=(address)=>{
	uni.setStorageSync("address",address)
	uni.navigateBack()
}
onShow(()=>{
	uni.setStorageSync("address",)
	undate()	
})
const cityList = ref([
  '北京市', '上海市', '广州市', '深圳市', '杭州市',
  '南京市', '苏州市', '武汉市', '成都市', '重庆市'
]);

const bindCityChange = (e) => {
  address.value.city = cityList.value[e.detail.value];
};
</script>

<style scoped>
	.select{
		width: 20px;
		height: 20px;
	}
	.edit{
		width: 20px;
		height: 20px;
	}
	.form-container {
	  padding:0px 20px;
	 background-color: white;
	 margin-top: 20px
	}
	.form-item {
	  display: flex;
	  align-items: center;
	
	 padding: 15px   0px;
	  border-top: 1px solid gainsboro;;
	}
	.form-item label {
	  display: block;
	  margin-bottom: 5px;
	  font-size: 28rpx;
	  color: #666;
	}
	.form-item input {
	  width: 65%;
	  padding: 10px;
	 
	  border-radius: 6rpx;
	  font-size: 28rpx;
	}
.container {
	min-height: 100vh;
	background-color: #f5f5f5;
}

.header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx 30rpx;
	background-color: #ffffff;
	border-bottom: 1rpx solid #eee;
	position: sticky;
	top: 0;
	z-index: 100;
}

.back-icon {
	font-size: 40rpx;
	color: #333;
}

.title {
	font-size: 32rpx;
	font-weight: 500;
	color: #333;
	margin: 0 auto;
}

.new-address {
	font-size: 28rpx;
	color: #333;
}

.address-list {
	padding: 20rpx;
}

.address-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	background-color: #ffffff;
	padding: 30rpx;
	margin-bottom: 20rpx;
	border-radius: 12rpx;
}

.address-info {
	flex: 1;
	margin-right: 20rpx;
}

.user-info {
	margin-bottom: 10rpx;
}

.name {
	font-size: 32rpx;
	color: #333;
	margin-right: 20rpx;
}

.phone {
	font-size: 32rpx;
	color: #666;
}

.address-detail {
	font-size: 28rpx;
	color: #666;
	line-height: 1.4;
}

.edit-icon {
	padding: 10rpx;
	color: #999;
}

.iconfont {
	font-family: "iconfont";
}
.city-input-container {
  display: flex;
  align-items: center;
  width: 65%;
}

.city-picker {
  margin-left: 5px;
  padding: 5px 10px;
  border-radius: 4px;
  font-size: 14px;
  color: #666;
  cursor: pointer;
}
</style>
